package vn.nad.aoeclips.screen.splash.controller;

import java.io.IOException;

import vn.nad.android.aoeclips.R;
import vn.nad.aoeclips.common.utils.Logger;
import vn.nad.aoeclips.common.utils.NetworkHelper;
import vn.nad.aoeclips.common.view.AlertDialogManager;
import vn.nad.aoeclips.notification.Config;
import vn.nad.aoeclips.screen.category.controller.MainActivity;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

/**
 * @author ducna6417
 */
// Regist push notification

public class SplashActivity extends Activity {
	private int TIME_SPLASH = 3000;

	GoogleCloudMessaging gcm;
	Context context;
	String regId;
	private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	public static final String REG_ID = "regId";
	private static final String TAG = SplashActivity.class.getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if (NetworkHelper.hasNetworkConnection(SplashActivity.this)) {
					Intent intent = new Intent(SplashActivity.this,
							MainActivity.class);
					startActivity(intent);
					finish();
				} else {
					AlertDialogManager.showAlert(SplashActivity.this,
							getString(R.string.no_network),
							new OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							});
				}

			}
		}, TIME_SPLASH);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// Regist push
		registerGCM();
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If it
	 * doesn't, display a dialog that allows users to download the APK from the
	 * Google Play Store or enable it in the device's system settings.
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(TAG, "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	/**
	 * register GCM Check device support play service
	 * 
	 * 
	 */
	public void registerGCM() {
		// Check device for Play Services APK. If check succeeds, proceed with
		// GCM registration.
		if (checkPlayServices()) {
			gcm = GoogleCloudMessaging.getInstance(this);
			regId = getRegistrationId(context);

			if (TextUtils.isEmpty(regId)) {
				registerInBackground();

				Logger.d("RegisterActivity",
						"registerGCM - successfully registered with GCM server - regId: "
								+ regId);
			} else {
				Logger.d("RegisterActivity", regId);
			}
		} else {
			Logger.i(TAG, "No valid Google Play Services APK found.");
		}
	}

	/**
	 * Gets the current registration ID for application on GCM service, if there
	 * is one.
	 * <p>
	 * If result is empty, the app needs to register.
	 * 
	 * @return registration ID, or empty string if there is no existing
	 *         registration ID.
	 */
	private String getRegistrationId(Context context) {
		String registrationId = getGcmPreferences(context);
		if (registrationId.equals("")) {
			Logger.i(TAG, "Registration not found.");
			return "";
		}
		return registrationId;
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */

	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and the app versionCode in the application's
	 * shared preferences.
	 */
	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regId = gcm.register(Config.GOOGLE_PROJECT_ID);
					Logger.d("RegisterActivity",
							"registerInBackground - regId: " + regId);
					msg = "Device registered, registration ID=" + regId;

					storeRegistrationId(context, regId);

					// Persist the regID - no need to register again.
					storeRegistrationId(context, regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					// If there is an error, don't just keep trying to register.
					// Require the user to click a button again, or perform
					// exponential back-off.
				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
			}
		}.execute(null, null, null);
	}

	/**
	 * Stores the registration ID and the app versionCode in the application's
	 * {@code SharedPreferences}.
	 * 
	 * @param context
	 *            application's context.
	 * @param regId
	 *            registration ID
	 */
	private void storeRegistrationId(Context context, String regId) {

	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private String getGcmPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences,
		// but
		// how you store the regID in your app is up to you.\
		return "";
	}
}
